# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from cec.rules import *
from cec.dao.sku_pool_dao import SkuPoolDao
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.done_filter import DoneFilter
from datetime import datetime
from cec.dao.catalog_dao import cec_CatalogDao
from zc_core.spiders.base import BaseSpider

class FullSpider(BaseSpider):
    name = 'full'

    # 商品详情页
    item_url = 'https://mall.cec-ec.com.cn/goods-{}.html'

    # sha
    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo,*args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)

    def start_requests(self):
        pool_list = SkuPoolDao().get_sku_pool_list()
        settings = get_project_settings()
        while_list = settings.get("CATALOG_WHITE_LIST")
        if while_list:
            pool_list = SkuPoolDao().get_sku_pool_list(
                query={"$or": while_list})
        self.logger.info('全量：%s' % (len(pool_list)))
        # 查询分页池
        # pool_2_list = cec_CatalogDao().get_cat_list_from_pool()
        for sku in pool_list:
            sku_id = sku.get('_id')
            soldCount = sku.get('soldCount')
            supplier_name = sku.get('supplierName')
            offline_time = sku.get('offlineTime', 0)
            settings = get_project_settings()
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', sku_id, offline_time)
                continue
            # 避免重复采集
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', sku_id)
                continue
            # 采集商品
            yield Request(
                url=self.item_url.format(sku_id),
                callback=self.parse_item_data,
                errback=self.error_back,
                priority=260,
                meta={
                    'reqType': 'item',
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                    'catalog3Id': sku.get('catalog3Id'),
                    'soldCount': soldCount,
                    'supplierName': supplier_name
                },
            )

    # 处理ItemData
    def parse_item_data(self, response):
        # 处理商品详情页
        data = parse_item_data(response)
        self.logger.info('商品: [%s]' % data.get('skuId'))
        yield data


